const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const router = new Router()

const koaBody = require('koa-body')
app.use(koaBody.default())

const cors = require('koa2-cors')
app.use(cors())

const mongoose = require('mongoose')

const User = require('../models/user')
const Driver = require('../models/driver')
const Order = require('../models/order')
const Admin = require('../models/admin')
//////////////////////////////登录///////////////////////////////////////
router.post("/ulogin", async (ctx, next) => {
	await next()
	// console.log('123')
	let utel = ctx.request.body["utel"]
	let upassword = ctx.request.body["upassword"]
	if (utel == undefined || utel == '') {
		ctx.body = {msg:"用户电话不能为空"}
		return
	}
	if (upassword == undefined || upassword == '') {
		ctx.body = {msg:"用户密码不能为空"}
		return
	}
	// 去MongoDB判断改用户是否存在
	let result = await User.find({
		'utel': utel,
		'upassword': upassword
	}).then(res => {
		if (res.length > 0) {
			return {msg:"用户登录成功",err:"",code:1,_id:res[0]._id}
		} else {
			return {msg:"用户登录失败",err:"",code:2}
		}
	}).catch(err => {
		return {msg:"用户登录失败",err:err,code:2}
	})

	ctx.body = result

})
///////////////////////////////注册//////////////////////////////////
router.post("/regist", async (ctx, next) => {
	await next()
	// let uname = ctx.request.body["uname"]
	// let uimg = ctx.request.body["uimg"]
	let utel = ctx.request.body["utel"]
	let upassword = ctx.request.body["upassword"]
	if (utel == undefined || utel == '') {
		ctx.body = {msg:"用户电话不能为空",err:""}
		return
	}
	if (upassword == undefined || upassword == '') {
		ctx.body = {msg:"用户密码不能为空",err:""}
		return
	}
	// if (uname == undefined || uname == '') {
	// 	ctx.body = {msg:"用户名称不能为空",err:""}
	// 	return
	// }
	let result = await new User({
		// uname, 
		upassword,
		utel
		// uimg
	}).save().then(() => {
		return {msg:"用户保存成功",err:"",code:1}
	}).catch(err => {
		return {msg:"用户保存不成功",err:"",code:2}
	})

	ctx.body = result

})

app.use(router.routes())
app.listen(3000,err => {
	if(err) console.error(err)
	console.log('3000已开启')
	mongoose.connect('mongodb://127.0.0.1:27017/cyyc')
})